package com.adcc.loadsheet.monitor.util;

import com.adcc.aoc.devLib.common.log.Log;
import com.google.common.base.Strings;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * HttpClient工具
 */
public class RestClient {

    public static int SOCKET_TIMEOUT = 10;
    public static int SOCKET_LONG_TIMEOUT = 30;

    public static int CONNECT_TIMEOUT = 10;
    public static int CONNECT_LONG_TIMEOUT = 30;

    public static int CONNECTION_REQUEST_TIMEOUT = 10;
    public static int CONNECTION_REQUEST_LONG_TIMEOUT = 30;

    /**
     * 执行GET请求
     * @param url
     * @return
     */
    public static String get(String url) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try{
            client = HttpClients.createDefault();
            HttpGet get = new HttpGet(url);
            RequestConfig config = RequestConfig.custom()
                    .setSocketTimeout(SOCKET_TIMEOUT * 1000)
                    .setConnectTimeout(CONNECT_TIMEOUT * 1000)
                    .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT * 1000).build();
            get.setConfig(config);
            get.addHeader("Content-type","application/json;charset=UTF-8");
            get.addHeader("Accept","application/json");
            response = client.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == 200 || statusCode == 500 || statusCode == 503){
                return EntityUtils.toString(response.getEntity());
            }else{
                Log.error(RestClient.class,"execute() error status code:" + response.getStatusLine().getStatusCode());
                return null;
            }
        }catch (Exception ex){
            Log.error(RestClient.class,"get() error",ex);
            return null;
        }finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException ex) {
                    Log.error(RestClient.class,"close io error",ex);
                }
            }
            if(client != null){
                try {
                    client.close();
                } catch (IOException ex) {
                    Log.error(RestClient.class,"close io error",ex);
                }
            }
        }
    }

    /**
     * 执行GET请求 超时时间较长
     * @param url
     * @return
     */
    public static String longGet(String url) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try{
            client = HttpClients.createDefault();
            HttpGet get = new HttpGet(url);
            RequestConfig config = RequestConfig.custom()
                    .setSocketTimeout(SOCKET_LONG_TIMEOUT * 1000)
                    .setConnectTimeout(CONNECT_LONG_TIMEOUT * 1000)
                    .setConnectionRequestTimeout(CONNECTION_REQUEST_LONG_TIMEOUT * 1000).build();
            get.setConfig(config);
            get.addHeader("Content-type","application/json;charset=UTF-8");
            get.addHeader("Accept","application/json");
            response = client.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == 200 || statusCode == 500 || statusCode == 503){
                return EntityUtils.toString(response.getEntity());
            }else{
                Log.error(RestClient.class,"execute() error status code:" + response.getStatusLine().getStatusCode());
                return null;
            }
        }catch (Exception ex){
            Log.error(RestClient.class,"longGet() error",ex);
            return null;
        }finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException ex) {
                    Log.error(RestClient.class,"close io error",ex);
                }
            }
            if(client != null){
                try {
                    client.close();
                } catch (IOException ex) {
                    Log.error(RestClient.class,"close io error",ex);
                }
            }
        }
    }

    /**
     * 访问url，返回请求状态
     * @param url
     * @return
     */
    public static boolean connect(String url) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try{
            client = HttpClients.createDefault();
            HttpGet get = new HttpGet(url);
            RequestConfig config = RequestConfig.custom()
                    .setSocketTimeout(SOCKET_TIMEOUT * 1000)
                    .setConnectTimeout(CONNECT_TIMEOUT * 1000)
                    .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT * 1000).build();
            get.setConfig(config);
            get.addHeader("Content-type","application/json;charset=UTF-8");
            get.addHeader("Accept","application/json");
            response = client.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == 200){
                return true;
            }else{
                Log.error(RestClient.class,"execute() error status code:" + response.getStatusLine().getStatusCode());
                return false;
            }
        }catch (Exception ex){
            Log.error(RestClient.class,"connect() error",ex);
            return false;
        }finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException ex) {
                    Log.error(RestClient.class,"close io error",ex);
                }
            }
            if(client != null){
                try {
                    client.close();
                } catch (IOException ex) {
                    Log.error(RestClient.class,"close io error",ex);
                }
            }
        }
    }

    /**
     * 执行POST请求
     * @param url
     * @return
     */
    public static String post(String url,String json) throws Exception{
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try{
            client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            RequestConfig config = RequestConfig.custom()
                    .setSocketTimeout(SOCKET_TIMEOUT * 1000)
                    .setConnectTimeout(CONNECT_TIMEOUT * 1000)
                    .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT * 1000).build();
            post.setConfig(config);
            post.addHeader("Content-type","application/json;charset=UTF-8");
            post.addHeader("Accept","application/json");
            if(!Strings.isNullOrEmpty(json)){
                StringEntity entity = new StringEntity(json, Charset.forName("UTF-8"));
                post.setEntity(entity);
            }
            response = client.execute(post);
            if(response.getStatusLine().getStatusCode() == 200){
                return EntityUtils.toString(response.getEntity());
            }else{
                Log.error(RestClient.class,"execute() error status code:" + response.getStatusLine().getStatusCode());
                throw new Exception("execute() error status code:" + response.getStatusLine().getStatusCode());
            }
        }catch (Exception ex){
            Log.error(RestClient.class,"post() error",ex);
            throw ex;
        }finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException ex) {
                    Log.error(RestClient.class,"close io error",ex);
                }
            }
            if(client != null){
                try {
                    client.close();
                } catch (IOException ex) {
                    Log.error(RestClient.class,"close io error",ex);
                }
            }
        }
    }

    /**
     * 执行POST请求
     * @param url
     * @param list
     * @return
     * @throws Exception
     */
    public static String post(String url,List<BasicNameValuePair> list) throws Exception{
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try{
            client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            RequestConfig config = RequestConfig.custom()
                    .setSocketTimeout(SOCKET_TIMEOUT * 1000)
                    .setConnectTimeout(CONNECT_TIMEOUT * 1000)
                    .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT * 1000).build();
            post.setConfig(config);
            if(list != null && list.size() > 0){
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list);
                post.setEntity(entity);
            }
            response = client.execute(post);
            if(response.getStatusLine().getStatusCode() == 200){
                return EntityUtils.toString(response.getEntity());
            }else{
                Log.error(RestClient.class,"execute() error status code:" + response.getStatusLine().getStatusCode());
                throw new Exception("execute() error status code:" + response.getStatusLine().getStatusCode());
            }
        }catch (Exception ex){
            Log.error(RestClient.class,"post() error",ex);
            throw ex;
        }finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException ex) {
                    Log.error(RestClient.class,"close io error",ex);
                }
            }
            if(client != null){
                try {
                    client.close();
                } catch (IOException ex) {
                    Log.error(RestClient.class,"close io error",ex);
                }
            }
        }
    }
}
